﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Forms;

namespace test
{
    public partial class screen : Form
    {

        private Socket Client;//创建通讯对象
        static Socket server;
        string IP;
        string port;
        byte[] dataReceive = new byte[1024];

        public screen()
        {
            InitializeComponent();
            this.FormClosed += (s, e) =>
              {
                  DisConnect();
              };
            textBox_Recive.ReadOnly = true;
        }


        private void button_Connection_Click(object sender, EventArgs e)
        {
            IP = textBox_IP.Text;
            port = textBox_Port.Text;
            Connect(IP, port);
            if (Client.Connected)
            {
                textBox_Recive.Text = "连接成功";
                button_Connection.Enabled = false;
            }
            else
            {
                textBox_Recive.Text = "连接失败";
                button_Connection.Enabled = true;
            }
        }

        public void Connect(string ip, String port)
        {
            try
            {
                Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//实例化Socket通讯连接
                Client.SendTimeout = 1000;//设置发送超时时间
                Client.ReceiveTimeout = 1000;//设置接收超时时间
                IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Parse(ip), int.Parse(port));//实例化IP地址
                Client.BeginConnect(iPEndPoint, new AsyncCallback(onconnect), Client);
            }
            catch (Exception ex)
            {
                Invoke(new Action(() => textBox_Recive.Text = ex.Message));
            }

        }

        private void onconnect(IAsyncResult ar)
        {
            try
            {
                //Socket Client = (Socket)ar.AsyncState;//获取客户端socket
                Client.EndConnect(ar);
                Client.BeginReceive(dataReceive, 0, dataReceive.Length, SocketFlags.None, new AsyncCallback(OnReceive), Client);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                int length = Client.EndReceive(ar);
                byte[] data = new byte[length];
                Array.Copy(dataReceive, data, length);
                Invoke(new Action(() => textBox_Recive.Text = Encoding.UTF8.GetString(data)));
                Client.BeginReceive(dataReceive, 0, dataReceive.Length, SocketFlags.None, new AsyncCallback(OnReceive), Client);
            }
            catch (Exception ex)
            {
                Invoke(new Action(() => textBox_Recive.Text = ex.Message));
            }
        }

        public void DisConnect()
        {
            if (Client != null)
            {
                Client.Shutdown(SocketShutdown.Both);//关闭连接
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Random r = new Random();
            string str = "";
            for (int i = 0; i < 6; i++)
            {
                str += r.Next(0, 10).ToString();
            }
            Console.WriteLine(str);
        }

        private void button_Send_Click(object sender, EventArgs e)
        {
            if (Client.Connected)
                Client.Send(Encoding.UTF8.GetBytes(textBox_ClientSend.Text));
            else
                textBox_Recive.Text = "未连接";
        }
    }
}
